import {Button, Dropdown, Input, message, Radio} from 'antd';
import React, {useState, useEffect} from "react";
import axios from "axios";

const Btn2 = (props) => {

    //根据经纬度查
    const [queryMethod, setQueryMethod] = useState(true);
    let lon
    let lat
    const onClick = ({key}) => {
        if(key ==='1'){
            setQueryMethod(true)
        }else{
            setQueryMethod(false)
        }
    };
    const items = [
        {
            label: '按行政区划查询',
            key: '1',
        },
        {
            label: '按地区名称查询',
            key: '2',
        }
    ];
    const [value, setValue] = React.useState(true);
    const [detail, setDetail] = React.useState("输入设备名称");
    const [inputValue, setInputValue] = useState();

    const handleInputBlur = (e) => {
        setInputValue(e.target.value);
        //118.2260099776079,32.19507592105712
    };
    //判断输入框的值
    const isValidLatLng = (input) => {
        // 清理输入字符串，只保留数字、小数点、负号和逗号
        let cleanedInput = '';
        for (let i = 0; i < input.length; i++) {
            const char = input[i];
            if ((char >= '0' && char <= '9') || char === '.' || char === '-' || char === ',') {
                cleanedInput += char;
            }
        }

        // 将清理后的输入按逗号分隔成两个部分
        const parts = cleanedInput.split(',');
        if (parts.length !== 2) return alert("不合法经纬度！请检查是否有中文字符！");

        // 解析这两个部分为浮点数
        lon = parseFloat(parts[0]);
        lat = parseFloat(parts[1]);

        // 检查解析结果是否为数字，以及是否在有效范围内
        if (isNaN(lat) || isNaN(lon)) return alert("不合法数字！");
        if (lat < -90 || lat > 90) return alert("纬度不在合理范围！");
        if (lon < -180 || lon > 180) return alert("经度不在合理范围！");

        return true;
    };

    const searchInLonLat = () => {
        if (isValidLatLng(inputValue)) {
            axios.get(`/weather-api/v2.6/QxR1YH5GOjqUl8EB/${lon},${lat}/hourly?hourlysteps=24`)
                .then(req => {
                    props.onClick(req.data.result.hourly.humidity, req.data.result.hourly.precipitation, true)
                })
                .catch(error => {
                    console.error('出错了:', error);
                })
        }
    }

    // 根据行政区查
    const [geoData, setGeoData] = useState([]);

    useEffect(() => {
        axios.get('https://geo.datav.aliyun.com/areas_v3/bound/320100_full.json')
            .then(req => {
                setGeoData(req.data);
            })
            .catch(error => {
                console.error('出错了:', error);
            });

    }, []);


    const searchInArea = () => {
        const foundCity = geoData.features.find(item => item.properties.name === inputValue)
        if (foundCity) {
            const newCityLon = foundCity.properties.center;
            lon = newCityLon[0];
            lat = newCityLon[1];
            axios.get(`/weather-api/v2.6/QxR1YH5GOjqUl8EB/${lon},${lat}/hourly?hourlysteps=24`)
                .then(req => {
                    props.onClick(req.data.result.hourly.humidity, req.data.result.hourly.precipitation, true)
                })
                .catch(error => {
                    console.error('出错了:', error);
                })
        } else {
            alert("没找到，请输入正确区划名！")
        }
    }

    //Radio变化时
    const handleRadioChange = (event) => {
        const isLonLat = event.target.value;
        console.log(isLonLat)
        setValue(isLonLat);
        setInputValue('');
        props.setMapActive(isLonLat);
        setDetail(isLonLat ?  "输入设备名称":"输入行政区");
        if(isLonLat===false&& queryMethod===false){
            setDetail("输入地区名称")
        }
    };

    return (
        <div style={{display: 'flex', margin: '0px 17px', width: '100%', alignItems: 'center'}}>
            <Dropdown
                menu={{
                    items,
                    onClick,
                }}
            >
                <a onClick={(e) => e.preventDefault()}
                   style={{color: '#333b46', fontSize: 15}}>{items[0].name}
                    <div>
                        天气查询方式：
                    </div>
                </a>
            </Dropdown>
            <div style={{margin: '3px 0px 0px 3px'}}>
                <Radio.Group name="radiogroup" defaultValue={true} onChange={handleRadioChange}>
                    <Radio value={false}>{queryMethod? "行政区划":"地区名称"}</Radio>
                    <Radio value={true}>设备位置</Radio>
                </Radio.Group>
            </div>
            <Input placeholder={detail}
                   value={inputValue}
                   onBlur={handleInputBlur}
                   onChange={handleInputBlur}
                   style={{width: '30%', marginRight: "20px", marginLeft: "15px"}}
                   allowClear
            >
            </Input>
            <Button type={"primary"} onClick={value? searchInLonLat:searchInArea}>查询天气</Button>
        </div>
    )
}

export default Btn2
